﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace _4_08_序列化单个对象
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //信息存入Student对象中
            Student student = new Student();
            student.StuId = Convert.ToInt32(this.idText.Text);//Convert.Toint本质上就是 调用 int.Parse
            student.StuName = this.nameText.Text;
            student.StuAge = int.Parse(this.agetext.Text);

            //创建文件将对象存入序列化文件中
            //stu.ini会指向当前文件夹的\bin\Debug
            FileStream fs = new FileStream("stu.ini",FileMode.Create,FileAccess.ReadWrite);//文件流
            BinaryFormatter bf =new BinaryFormatter();//二进制序列化格式化器
            bf.Serialize(fs, student);//将student对象序列化存入文件流中
            fs.Close();
            MessageBox.Show("学生信息保存成功！");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //读取信息反序列化 将二进制读出 指向原对象并显示出来
            FileStream fs = new FileStream("stu.ini", FileMode.Open, FileAccess.ReadWrite);
            BinaryFormatter bf = new BinaryFormatter();
            Student student =(Student)bf.Deserialize(fs);//将文件流反序列化
            this.idText.Text = student.StuId.ToString();
            this.nameText.Text = student.StuName;
            this.agetext.Text = student.StuAge.ToString();
            fs.Close();
        }
    }
}
